package com.yl.chainStore.services.impl.warehouse

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.entity.warehouse.*
import com.yl.chainStore.mapper.warehouse.*
import com.yl.chainStore.services.warehouse.IWarehouseService
import com.yl.chainStore.services.warehouse.IWarehouseCheckOrderService
import com.yl.chainStore.services.warehouse.IWarehouseProfitLossOrderService
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.services.ICompanyUserService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class WarehouseCheckOrderServiceImpl(
	private val warehouseCheckOrderMapper: WarehouseCheckOrderMapper,
	private val warehouseCheckOrderDetailMapper: WarehouseCheckOrderDetailMapper
) : IWarehouseCheckOrderService {

	companion object {
		private val log = LoggerFactory.getLogger(IWarehouseCheckOrderService::class.java)
	}

	@Autowired
	lateinit var iWarehouseService: IWarehouseService

	@Autowired
	lateinit var iWarehouseProfitLossOrderService: IWarehouseProfitLossOrderService

	@Autowired
	lateinit var iCompanyUserService: ICompanyUserService
	override fun addDetail(detail: WarehouseCheckOrderDetail): ResponseBody {
		log.info("盘点单：添加信息明细 detail{}", detail)
		warehouseCheckOrderDetailMapper.insert(detail)
		return returnSuccess()
	}

	override fun getCheckOrder(id: Long): WarehouseCheckOrder? {
		log.info("盘点单：获取盘点单基本信息 id{}", id)
		val order = warehouseCheckOrderMapper.selectById(id) ?: return null
		val user = iCompanyUserService.getUser(order.createUserId)
		if (user != null) {
			order.createUserName = user.realName
		}
		val checkUser = iCompanyUserService.getUser(order.checkUserId!!)
		if (checkUser != null) {
			order.checkUserName = checkUser.realName
		}
		if (order.dealUserId != null) {
			val dealUser = iCompanyUserService.getUser(order.dealUserId!!)
			if (dealUser != null) {
				order.dealUserName = dealUser.realName
			}
		}
		return order
	}

	override fun getOrderDetails(orderId: Long): List<WarehouseCheckOrderDetail> {
		log.info("盘点单：获取盘点单明细列表 orderId：{}", orderId)
		return warehouseCheckOrderDetailMapper.selectListByOrderId(orderId)
	}

	override fun completeCheckOrder(id: Long): ResponseBody {
		log.info("盘点单：完成盘点单 orderId：{}", id)
		val warehouseCheckOrder =
			warehouseCheckOrderMapper.selectById(id) ?: return returnError(ErrorCode.PARAM_EMPTY, "未找到盘点订单")
		warehouseCheckOrder.details =
			warehouseCheckOrderDetailMapper.selectListByOrderId(id)
		return completeCheckOrder(warehouseCheckOrder)
	}

	override fun completeCheckOrder(checkOrder: WarehouseCheckOrder): ResponseBody {
		log.info("盘点单：完成盘点单 checkOrder：{}", checkOrder)
		checkOrder.dealUserId = getContext().userId
		if (!checkOrder.details.isNullOrEmpty()) {
			//创建一个损益单
			val plOrder = WarehouseProfitLossOrder(
				id = 0L,
				createUserId = checkOrder.createUserId,
				orderUserId = checkOrder.createUserId,
				deptId = checkOrder.deptId,
				companyId = checkOrder.companyId,
				orderType = TypeEnum.WAREHOUSE_PROFIT_LOSS_TYPE_CHECK_ORDER,
				status = Status.WAIT_AUDIT,
				remark = checkOrder.remark,
				orderTime = checkOrder.checkTime
			)
			val addProfitLossOrder = iWarehouseService.addProfitLossOrder(plOrder)
			if (addProfitLossOrder.code != ErrorCode.SUCCESS.code) {
				return addProfitLossOrder
			}
			for (detail in checkOrder.details!!) {
				log.info("盘点单：盘点确认：明细确认：detail{}", detail)
				detail.status = Status.COMPLETE

				var goodCount = detail.gapCount
				if (detail.gapCount == 0) {
					continue
				}
				val addDetail = iWarehouseProfitLossOrderService.addDetail(
					WarehouseProfitLossOrderDetail(
						id = 0L,
						goodCount = goodCount,
						itemId = detail.itemId,
						price = 0L,
						status = Status.WAIT_AUDIT,
						orderId = plOrder.id,
						remark = detail.remark
					)
				)
				if (addDetail.code != ErrorCode.SUCCESS.code) {
					return addProfitLossOrder
				}
				warehouseCheckOrderDetailMapper.updateById(detail)
			}
			iWarehouseProfitLossOrderService.completeOrder(plOrder.id)
		}
		checkOrder.status = Status.COMPLETE
		warehouseCheckOrderMapper.updateById(checkOrder)
		return returnSuccess()
	}

	override fun cancelCheckOrder(id: Long): ResponseBody {
		log.info("仓库订单管理：取消盘点：id{}", id)
		val checkOrder =
			warehouseCheckOrderMapper.selectById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到调度单")
		if (checkOrder.status != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		val details =
			warehouseCheckOrderDetailMapper.selectList(
				QueryWrapper<WarehouseCheckOrderDetail?>().eq(
					"check_order_id",
					id
				)
			)
		checkOrder.dealUserId = getContext().userId
		checkOrder.status = Status.SCRAP
		if (!details.isNullOrEmpty()) {
			for (detail in details) {
				detail.status = Status.SCRAP
				warehouseCheckOrderDetailMapper.updateById(detail)
			}
		}
		warehouseCheckOrderMapper.updateById(checkOrder)
		return returnSuccess()
	}

	override fun noPassCheckOrder(id: Long): ResponseBody {
		log.info("仓库订单管理：审核不通过：id{}", id)
		val checkOrder =
			warehouseCheckOrderMapper.selectById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到调度单")
		if (checkOrder.status != Status.WAIT_AUDIT) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "订单已被处理")
		}
		val details =
			warehouseCheckOrderDetailMapper.selectList(
				QueryWrapper<WarehouseCheckOrderDetail?>().eq(
					"check_order_id",
					id
				)
			)
		checkOrder.dealUserId = getContext().userId
		checkOrder.status = Status.NO_PASS
		if (!details.isNullOrEmpty()) {
			for (detail in details) {
				detail.status = Status.NO_PASS
				warehouseCheckOrderDetailMapper.updateById(detail)
			}
		}
		warehouseCheckOrderMapper.updateById(checkOrder)
		return returnSuccess()
	}

	override fun deleteCheckOrder(orderId: Long): ResponseBody {
		log.info("盘点单 ==>删除：id{}", orderId)
		val outOrder = warehouseCheckOrderMapper.selectById(orderId) ?: return returnSuccess()
		if (outOrder.status.code > Status.WAIT_AUDIT.code) {
			return returnError(ErrorCode.DATA_DELETE_FAILED, "订单已被处理")
		}
		warehouseCheckOrderMapper.deleteById(orderId)
		return returnSuccess()
	}

}
